package com.team2.insulatingtools.modular.tools.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.pojo.response.ErrorResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.team2.insulatingtools.modular.tools.entity.ToolDetail;
import com.team2.insulatingtools.modular.tools.entity.Tools;
import com.team2.insulatingtools.modular.tools.enums.ToolDetailExceptionEnum;
import com.team2.insulatingtools.modular.tools.mapper.ToolDetailMapper;
import com.team2.insulatingtools.modular.tools.mapper.ToolsMapper;
import com.team2.insulatingtools.modular.tools.dto.ToolDetailDto;
import com.team2.insulatingtools.modular.tools.dto.ToolDetailQueriedDto;
import com.team2.insulatingtools.modular.tools.pojo.request.*;
import com.team2.insulatingtools.modular.tools.service.ToolDetailService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Date;

/**
 * 工具详细信息 业务实现层
 *
 * @author team2
 * @date 2023/04/03 09:48
 */
@Service
public class ToolDetailServiceImpl extends ServiceImpl<ToolDetailMapper, ToolDetail> implements ToolDetailService {
    @Resource
    private ToolDetailMapper mapper;

    @Resource
    private ToolDetailMapper toolDetailMapper;

    private static final String DEFAULT_WORKSHOP = "郑州供电车间";
    private static final String DEFAULT_TOOL = "接地杆";
    private static final Integer DEFAULT_CURRENT_PAGE = 1;
    private static final Integer DEFAULT_PAGE_SIZE = 5;

    @Resource
    private ToolsMapper toolsMapper;

    @Override
    public void add(ToolDetailRequest toolDetailRequest) {
        ToolDetail toolDetail = new ToolDetail();
        BeanUtil.copyProperties(toolDetailRequest, toolDetail);
        this.save(toolDetail);
    }

    @Override
    public void del(ToolDetailRequest toolDetailRequest) {
        ToolDetail toolDetail = this.queryToolDetail(toolDetailRequest);
        this.removeById(toolDetail.getId());
    }

    @Override
    public void edit(ToolDetailRequest toolDetailRequest) {
        ToolDetail toolDetail = this.queryToolDetail(toolDetailRequest);
        Tools tools = toolsMapper.selectById(toolDetail.getToolId());
        BeanUtil.copyProperties(toolDetailRequest, toolDetail);
        toolDetail.setCycle(tools.getCycle());
        toolDetail.setWorkingVoltage(tools.getWorkingVoltage());
        toolDetail.setLength(tools.getLength());
        toolDetail.setCycle(tools.getCycle());
        toolDetail.setLastingTime(tools.getLastingTime());
        //有效日期根据基础信息管理中试验周期（月）来确定
        if (toolDetail.getTestDate()!=null){
            //有效日期根据基础信息管理中试验周期（月）来确定
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(toolDetail.getTestDate());
            calendar.add(Calendar.MONTH,toolDetail.getCycle().intValue());
            toolDetail.setExpireDate(calendar.getTime());
        }
        this.updateById(toolDetail);
    }

    @Override
    public ToolDetail detail(ToolDetailRequest toolDetailRequest) {
        return this.queryToolDetail(toolDetailRequest);
    }

    @Override
    public PageResult<ToolDetail> findPage(ToolDetailRequest toolDetailRequest) {
        LambdaQueryWrapper<ToolDetail> wrapper = createWrapper(toolDetailRequest);
        Page<ToolDetail> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(sysRolePage);
    }

    @Override
    public List<ToolDetail> findList(ToolDetailRequest toolDetailRequest) {
        LambdaQueryWrapper<ToolDetail> wrapper = this.createWrapper(toolDetailRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author team2
     * @date 2023/04/03 09:48
     */
    private ToolDetail queryToolDetail(ToolDetailRequest toolDetailRequest) {
        ToolDetail toolDetail = this.getById(toolDetailRequest.getId());
        if (ObjectUtil.isEmpty(toolDetail)) {
            throw new ServiceException(ToolDetailExceptionEnum.TOOL_DETAIL_NOT_EXISTED);
        }
        return toolDetail;
    }

    @Override
    public ToolDetail queryById(Integer id) {
        return toolDetailMapper.selectById(id);
    }

    @Override
    public Tools updateToolsUsingToolDetail(ToolDetailRequest toolDetailRequest) {
        Integer toolDetailId = updateById(toolDetailRequest).getId();
        ToolDetail toolDetail = toolDetailMapper.selectById(toolDetailId);
        Tools tools = new Tools();
        tools.setId(toolDetail.getToolId());
        tools.setTestDate(toolDetail.getTestDate());
        tools.setTester(toolDetail.getTester());
        tools.setAuditor(toolDetail.getAuditor());
        tools.setOperateDate(toolDetail.getOperateDate());
        tools.setOperateConclusion(toolDetail.getOperateConclusion());

        toolsMapper.updateById(tools);

        return tools;
    }

    @Override
    public List<ToolDetail> updateByMultipleId(MultipleToolDetailRequest multipleToolDetailRequest) {
        List<ToolDetail>toolDetailList = new ArrayList<>();
        int listLength = multipleToolDetailRequest.getIdList().length;
        for (int i = 0; i < listLength; i++) {
            ToolDetailRequest toolDetailRequest = new ToolDetailRequest();
            toolDetailRequest.setId(multipleToolDetailRequest.getIdList()[i]);
            toolDetailRequest.setTestDate(multipleToolDetailRequest.getTestDate());
            toolDetailRequest.setTester(multipleToolDetailRequest.getTester());
            toolDetailRequest.setAuditor(multipleToolDetailRequest.getAuditor());
            toolDetailRequest.setOperateDate(multipleToolDetailRequest.getOperateDate());
            toolDetailRequest.setOperateConclusion(multipleToolDetailRequest.getOperateConclusion());

            toolDetailList.add(updateById(toolDetailRequest));
        }
        return toolDetailList;
    }

    @Override
    public List<Tools> updateMultipleToolsUsingMultipleToolDetails(MultipleToolDetailRequest multipleToolDetailRequest) {
        List<ToolDetail> toolDetailUpdateInformList = updateByMultipleId(multipleToolDetailRequest);
        List<ToolDetailRequest> toolDetailRequestList = new ArrayList<>();
        List<Tools> toolsList = new ArrayList<>();
        for (ToolDetail toolDetail : toolDetailUpdateInformList) {
            ToolDetailRequest toolDetailRequest = new ToolDetailRequest();
            toolDetailRequest.setId(toolDetail.getId());
            toolDetailRequest.setTestDate(toolDetail.getTestDate());
            toolDetailRequest.setTester(toolDetail.getTester());
            toolDetailRequest.setAuditor(toolDetail.getAuditor());
            toolDetailRequest.setOperateDate(toolDetail.getOperateDate());
            toolDetailRequest.setOperateConclusion(toolDetail.getOperateConclusion());

            toolDetailRequestList.add(toolDetailRequest);
        }

        for (ToolDetailRequest toolDetailRequest : toolDetailRequestList) {
            Tools tools = updateToolsUsingToolDetail(toolDetailRequest);
            toolsList.add(tools);
        }
        return toolsList;
    }

    /**
     * 创建查询wrapper
     *
     * @author team2
     * @date 2023/04/03 09:48
     */
    private LambdaQueryWrapper<ToolDetail> createWrapper(ToolDetailRequest toolDetailRequest) {
        LambdaQueryWrapper<ToolDetail> queryWrapper = new LambdaQueryWrapper<>();

        Integer id = toolDetailRequest.getId();
        Integer toolId = toolDetailRequest.getToolId();
        String number = toolDetailRequest.getNumber();
        Integer isMultisection = toolDetailRequest.getIsMultisection();
        String keeper = toolDetailRequest.getKeeper();
        String operateConclusion = toolDetailRequest.getOperateConclusion();
        Date testDate = toolDetailRequest.getTestDate();
        Date expireDate = toolDetailRequest.getExpireDate();
        String tester = toolDetailRequest.getTester();
        String auditor = toolDetailRequest.getAuditor();
        Date operateDate = toolDetailRequest.getOperateDate();
        Float workingVoltage = toolDetailRequest.getWorkingVoltage();
        Float testVoltage = toolDetailRequest.getTestVoltage();
        Float length = toolDetailRequest.getLength();
        Float lastingTime = toolDetailRequest.getLastingTime();
        Float cycle = toolDetailRequest.getCycle();
        String leakageCurrentNew = toolDetailRequest.getLeakageCurrentNew();
        String leakageCurrentRunning = toolDetailRequest.getLeakageCurrentRunning();
        Integer status = toolDetailRequest.getStatus();

        queryWrapper.eq(ObjectUtil.isNotNull(id), ToolDetail::getId, id);
        queryWrapper.eq(ObjectUtil.isNotNull(toolId), ToolDetail::getToolId, toolId);
        queryWrapper.like(ObjectUtil.isNotEmpty(number), ToolDetail::getNumber, number);
        queryWrapper.eq(ObjectUtil.isNotNull(isMultisection), ToolDetail::getIsMultisection, isMultisection);
        queryWrapper.like(ObjectUtil.isNotEmpty(keeper), ToolDetail::getKeeper, keeper);
        queryWrapper.eq(ObjectUtil.isNotNull(operateConclusion), ToolDetail::getOperateConclusion, operateConclusion);
        queryWrapper.eq(ObjectUtil.isNotNull(testDate), ToolDetail::getTestDate, testDate);
        queryWrapper.eq(ObjectUtil.isNotNull(expireDate), ToolDetail::getExpireDate, expireDate);
        queryWrapper.like(ObjectUtil.isNotEmpty(tester), ToolDetail::getTester, tester);
        queryWrapper.like(ObjectUtil.isNotEmpty(auditor), ToolDetail::getAuditor, auditor);
        queryWrapper.eq(ObjectUtil.isNotNull(operateDate), ToolDetail::getOperateDate, operateDate);
        queryWrapper.eq(ObjectUtil.isNotNull(workingVoltage), ToolDetail::getWorkingVoltage, workingVoltage);
        queryWrapper.eq(ObjectUtil.isNotNull(testVoltage), ToolDetail::getTestVoltage, testVoltage);
        queryWrapper.eq(ObjectUtil.isNotNull(length), ToolDetail::getLength, length);
        queryWrapper.eq(ObjectUtil.isNotNull(lastingTime), ToolDetail::getLastingTime, lastingTime);
        queryWrapper.eq(ObjectUtil.isNotNull(cycle), ToolDetail::getCycle, cycle);
        queryWrapper.like(ObjectUtil.isNotEmpty(leakageCurrentNew), ToolDetail::getLeakageCurrentNew, leakageCurrentNew);
        queryWrapper.like(ObjectUtil.isNotEmpty(leakageCurrentRunning), ToolDetail::getLeakageCurrentRunning, leakageCurrentRunning);
        queryWrapper.eq(ObjectUtil.isNotNull(status), ToolDetail::getStatus, status);

        return queryWrapper;
    }

    @Override
    public ToolDetail updateById(ToolDetailRequest toolDetailRequest) {
        ToolDetail toolDetail = new ToolDetail();
        BeanUtils.copyProperties(toolDetailRequest, toolDetail);
        toolDetailMapper.updateById(toolDetail);
        return toolDetail;
    }

    @Override
    public List<ToolDetailQueriedDto> pageByWorkshopAndTool(String workshopName, String toolName, Integer curr, Integer size) {
        IPage<?> toolDetailIPage = new Page<>();
        if (curr == null) {
            toolDetailIPage.setCurrent(DEFAULT_CURRENT_PAGE);
        } else {
            toolDetailIPage.setCurrent(curr);
        }
        if (size == null) {
            toolDetailIPage.setSize(DEFAULT_PAGE_SIZE);
        } else {
            toolDetailIPage.setSize(size);
        }

//        ToolDetailDto toolDetailDto = new ToolDetailDto(DEFAULT_WORKSHOP, DEFAULT_TOOL);
//        if (workshopName != null && toolName == null) {
//            toolDetailDto.setWorkshopName(workshopName);
//        } else if (workshopName == null && toolName != null) {
//            toolDetailDto.setToolName(toolName);
//        } else {
//            toolDetailDto.setWorkshopName(workshopName);
//            toolDetailDto.setToolName(toolName);
//        }

        ToolDetailDto toolDetailDto = new ToolDetailDto(workshopName, toolName);
        return toolDetailMapper.selectByWorkshopAndTool(toolDetailIPage, toolDetailDto);
    }


    @Override
    public ResponseData addToolsDetail(ToolDetailAddRequest request) {
        //1.获取父工具的信息
        Tools tools = toolsMapper.selectById(request.getToolId());
        if(tools!=null){
            //2.初始化分节信息
            ToolDetail toolDetail = new ToolDetail();
            BeanUtil.copyProperties(tools,toolDetail);
            BeanUtil.copyProperties(request,toolDetail);
            StringBuilder sb = new StringBuilder(tools.getNumber()+"-"+toolDetail.getNumber());
            toolDetail.setNumber(sb.toString());
            //3.设置父id
            toolDetail.setToolId(tools.getId());
            toolDetail.setId(0);
            if(toolDetailMapper.insert(toolDetail)>0){
                return new SuccessResponseData("增加具体内容成功");
            }
        }
        return new ErrorResponseData("10000","增加具体内容失败");
    }

    @Override
    public ResponseData delToolsDetail(int id) {
        if(mapper.deleteById(id)>0){
            return new SuccessResponseData("删除具体内容成功");
        }
        return new ErrorResponseData("10000","删除具体内容失败");
    }


    @Override
    public ResponseData selByTid(int tid) {
        List<ToolDetail> list = mapper.selectList(new QueryWrapper<ToolDetail>().eq("tool_id", tid));
        return new SuccessResponseData(list);
    }

    @Override
    public ResponseData pageByTid(int tid,int page,int size) {
        return new SuccessResponseData(
                mapper.selectListByTid(tid,new Page(page,size)));
    }

    @Override
    public void deleteBatchByToolIdList(List<Integer> toolIdList){
        this.mapper.deleteBatchByToolIdList(toolIdList);
    }

    @Override
    public void updateBatch(ToolDetailRequest toolDetailRequest){
        ToolDetail detail = new ToolDetail();
        BeanUtils.copyProperties(toolDetailRequest,detail);
        this.mapper.updateBatch(toolDetailRequest);
    }

}
